package com.springboot.study.aspjectj;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Author: guodong
 * @Date: 2021/6/29 16:13
 * @Version: 1.0
 * @Description:
 */
@Component
@Aspect
@Order
public class OperateLogAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.springboot.study.service.BusinessService.*(..)) && !execution(* com.springboot.study.service.BusinessService.getTest*(..)) ")
    private void log() {
    }

    @Before("log()")
    public void beforeMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        joinPoint.getArgs();
        logger.info("方法为:" + methodName + ", 这是一个前置测试 ");
    }

    @After("execution(* com.springboot.study.service.BusinessService.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        logger.info("方法为:" + methodName + ", 这是一个后置测试 ");
    }

    @Around("execution(* com.springboot.study.service.BusinessService.getTestInfo(..))")
    public void test(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        logger.info("方法为:" + methodName + ", 测水水水水水水水水水水 ");
    }

    @AfterReturning(value = "log()", returning = "result")
    public void afterReturning(JoinPoint point, Object result) {
        String methodName = point.getSignature().getName();
        logger.info("方法为：" + methodName + "，目标方法执行结果为：" + result);
    }

    @Around("log()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        logger.info("请求参数：{}", joinPoint.getArgs());
        Object[] arr = joinPoint.getArgs();
        Integer type = (Integer) arr[1];
        logger.info("请求类型：{}", type);
        long startTime = System.currentTimeMillis();
        Object obj = joinPoint.proceed();
        long timeTaken = System.currentTimeMillis() - startTime;
        logger.info("执行时间：{}", timeTaken);
        return obj;
    }
}
